<template>
    <Card>
        <Row type="flex" align="middle" :gutter="12" class="ivu-mb-8">
            <Col><DatePicker v-model="date" type="daterange" @on-change="changeAskData" placeholder="请选择时间" v-width="200"></DatePicker></Col>
            <Col><Button type="primary" @click="consumeChannel({id:''})" v-hasC="{name:'-v1-marketing-consume-update-consume',flag: '/v1/marketing/consume/update-consume'}">日消费录入</Button></Col>
            <Col><Button type="error" @click="consumeMonthChannel({id:''})"  v-hasC="{name:'-v1-marketing-consume-update-consume-month',flag: '/v1/marketing/consume/update-consume-month'}">设置平均日消费</Button></Col>
            <Col><Button type="primary" @click="unploadData" v-hasC="{name:'v1-marketing-consume-save-consume',flag: 'v1/marketing/consume/save-consume'}">上传数据</Button></Col>
        </Row>
        <Table :columns="columns" :data="data" :loading="loading">
            <template slot="footer">
                <Page
                    show-total show-elevator
                    show-sizer transfer
                    :total="total"
                    :current.sync="params.page"
                    :page-size="params.pageSize"
                    :page-size-opts="pageOpts"
                    @on-change="changepage"
                    @on-page-size-change="changepageSize"
                    style="text-align: center;"
                />
            </template>
        </Table>
         <Modal
            v-model="consume"
            title="日消费录入"
            width="800"
            @on-cancel="consumeCancel">
            <Row type="flex" align="middle" :gutter="12">
                <Col class="ivu-mb-8"><DatePicker v-model="consumeParams.date" :options="optionsConsume" :clearable="false" type="date" @on-change="consumeChannel" placeholder="请选择时间" v-width="120"></DatePicker></Col>
                <Col v-for="item in consumeAllList" :key="item.source_channel_id" class="ivu-mb-8"><Button :type="consumeParams.id === item.source_channel_id ? 'primary' : 'default'" @click="changeConsumeChannel(item)">{{item.source_name}}</Button></Col>
            </Row>
            <template v-for="item in consumeAllList">
                <Row type="flex" align="middle" :gutter="12" style="max-height:500px;overflow:auto" v-if="consumeParams.id === item.source_channel_id" :key="item.source_channel_id">
                    <Col v-for="items in item.children" :key="items.id" class="ivu-mb-8">
                        <span class="ivu-mr-8">{{items.source_name}}：</span>
                        <InputNumber :disabled="items.disabled" :min="0" v-model="items.consume" placeholder="请输入日消费"  v-width="120"></InputNumber>
                    </Col>
                </Row>
            </template>
            <div slot="footer">
                <Button @click="consumeCancel">取消</Button>
                <Button type="primary" @click="consumeSubmit" :disabled="disabled">提交</Button>
            </div>
        </Modal>
         <Modal
            v-model="consumeMonth"
            title="设置平均日消费"
            width="800"
            @on-cancel="consumeMonthCancel">
            <Row type="flex" align="middle" :gutter="12">
                <Col class="ivu-mb-8"><DatePicker v-model="consumeMonthParams.date" :options="optionsConsumeMonth" :clearable="false" type="month" @on-change="consumeMonthChannel" placeholder="请选择时间" v-width="120"></DatePicker></Col>
                <Col v-for="item in consumeMonthAllList" :key="item.source_channel_id" class="ivu-mb-8" v-if="+item.id!==596"><Button :type="consumeMonthParams.id === item.source_channel_id ? 'primary' : 'default'" @click="changeConsumeMonthChannel(item)">{{item.source_name}}</Button></Col>
            </Row>
            <template v-for="item in consumeMonthAllList">
                <Row type="flex" align="middle" :gutter="12" style="max-height:500px;overflow:auto" v-if="consumeMonthParams.id === item.source_channel_id" :key="item.source_channel_id">
                    <Col v-for="items in item.children" :key="items.id" class="ivu-mb-8">
                        <span class="ivu-mr-8">{{items.source_name}}：</span>
                        <InputNumber :min="0" v-model="items.consume" placeholder="请输入平均日消费"  v-width="140"></InputNumber>
                        <span class="ivu-ml-8">{{averagemoney(items.consume)}}</span>
                    </Col>
                </Row>
            </template>
            <div slot="footer">
                <Button @click="consumeMonthCancel">取消</Button>
                <Button type="primary" @click="consumeMonthSubmit" :disabled="disabled">提交</Button>
            </div>
        </Modal>
        <Modal v-model="modalStatus" title="上传数据" @on-cancel="cancelModal">
            <Row >
                <Col style="margin-left:25px;margin-top:5px"> 文件：</Col>
                <Col>
                    <div style="display:flex">
                        <Input v-model="imgSavePath"/>
                        <Upload :headers="upHeaders" ref="upload" :action="url + '/v1/marketing/consume/import-consume'" name="file"
                            :on-format-error="handleFormatError" :on-success="handleSuccess" :on-error="handleError"
                            :format="['xlsx','xls']" :data="formatParams" :before-upload="handleUpload" :show-upload-list="false"	>
                            <Button type="primary" icon="ios-cloud-upload-outline">浏览</Button>
                        </Upload>
                        <!-- <Button type="primary" @click="btnChange">浏览</Button> -->
                    </div>
                </Col>
            </Row>
             <Row style="margin-top:30px">
                <Col>模板下载：</Col>
                <Col><a  @click="downMB">消费数据模板.xls</a></Col>
            </Row>
            <div slot="footer">
                <Button @click="cancelModal">取消</Button>
                <Button type="primary" @click="saveModal" >确认</Button>
            </div>
        </Modal>
    </Card>
</template>

<script>
    import {
        marketingconsumeconsumelist,
        saveConsume,
        marketingconsumeupdateconsume,
        marketingconsumeupdateconsumemonth,
        marketingconsumegetconsume,
        marketingconsumegetconsumemonth
    } from '@/api/hqapi/networkMarketing.js';
      import util from "@/libs/util";
    export default {
        name: 'consumption',

        data () {
            const optionsConsumeMonth = {
                disabledDate (date) {
                    return date && date.valueOf() > this.$Date()
                }
            }
            return {
                optionsConsume: {
                    disabledDate (date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
                optionsConsumeMonth,
                disabled: false,
                loading: false,
                pageOpts: [10, 20, 50, 100],
                total: 0,
                data: [],
                columns: [],
                columnsDate: [{ title: '日期', key: 'date', fixed: 'left', width: 120 }],
                columnsTitle: [],
                date: [],
                params: { start_time: '', end_time: '', page: 1, pageSize: 20 },
                consumeAllList: [],
                consume: false,
                consumeMonth: false,
                consumeMonthAllList: [],
                consumeParams: { date: '', channel_id: '', id: '' },
                consumeMonthParams: { date: '', channel_id: '', id: '' },
                modalStatus:false,
                 url: "",
                upHeaders: {
                ProjectId: "",
                Authorization: "",
                MemberId: "",
                },
                formatParams:{},
                imgSavePath:'',
                file_type:'',
                path:'',
            };
        },

        mounted () {
            const token = util.cookies.get("token");
            let ProjectId = localStorage.getItem("currentProject");
            let MemberId = util.cookies.get("uuid");
            this.url = process.env.VUE_APP_API
            this.upHeaders.ProjectId = ProjectId
            this.upHeaders.Authorization = "Bearer " + token;
            this.upHeaders.MemberId = MemberId
            this.consumeParams.date = this.$Date().subtract(1, 'day').format('YYYY-MM-DD')
            this.consumeMonthParams.date = this.$Date().format('YYYY-MM')
            let time=[this.$Date().startOf('month').format('YYYY-MM-DD'), this.$Date().format('YYYY-MM-DD')]
            if(time[0]==time[1]){
                this.date = [this.$Date().startOf('month').format('YYYY-MM-DD'), this.$Date().format('YYYY-MM-DD')]
            }else{
               this.date = [this.$Date().startOf('month').format('YYYY-MM-DD'), (this.$Date(new Date()-3600*1000*24)).format('YYYY-MM-DD')]
            }
            // this.date = [this.$Date().subtract(1, 'day').format('YYYY-MM-DD'), this.$Date().subtract(1, 'day').format('YYYY-MM-DD')]
            this.params.start_time = this.date[0]
            this.params.end_time = this.date[1]
            this.initial()
        },
        methods: {
            initial () {
                // this.askDataChannel()
                this.askData()
            },
            // askDataChannel () {
            //     marketingconsumegetchannel().then(res => {
            //         this.channelList = res
            //     })
            // },
            askData () {
                this.loading = true
                marketingconsumeconsumelist(this.params).then(res => {
                    this.data = res.list.list
                    this.total = res.list.total
                    this.columnsTitle = res.header_list
                    this.columns = [ ...this.columnsDate, ...this.columnsTitle ]
                    this.loading = false
                })
            },
            changeAskData () {
                this.params.start_time = this.date[0]
                this.params.end_time = this.date[1]
                this.params.page = 1;
                this.askData()
            },
            changepage (e) {
                this.params.page = e;
                this.askData()
            },
            changepageSize (e) {
                this.params.page = 1;
                this.params.pageSize = e;
                this.askData()
            },
            averagemoney (money) {
                // console.log(money)
                if (!money && typeof money !== 'undefined' && money != 0) return ''
                else {
                    let day = this.$Date(this.consumeMonthParams.date).daysInMonth()
                    let averagemoney = Math.round((money * 100) / day) / 100
                    return `日消费 ${averagemoney}`
                }
            },
            changeConsumeChannel (item) {
                this.consumeParams.id = item.source_channel_id
            },
            consumeChannel (item) {
                this.consumeParams.channel_id = item.id
                let params = { date: this.$Date(this.consumeParams.date).format('YYYY-MM-DD'), channel_id: this.consumeParams.channel_id }
                marketingconsumegetconsume(params).then(res => {
                    this.consumeParams.id = res[0].source_channel_id
                    this.consumeAllList = res
                    this.consume = true
                })
            },
            changeConsumeMonthChannel (item) {
                this.consumeMonthParams.id = item.source_channel_id
            },
            consumeMonthChannel (item) {
                this.consumeMonthParams.channel_id = item.id
                let params = { date: this.$Date(this.consumeMonthParams.date).format('YYYY-MM'), channel_id: this.consumeMonthParams.channel_id }
                marketingconsumegetconsumemonth(params).then(res => {
                    this.consumeMonthParams.id = res[0].source_channel_id
                    this.consumeMonthAllList = res
                    this.consumeMonth = true
                })
            },
            // consumeUpdate () {
            //     this.consume = true
            //     this.consumeParams.channel_id = ''
            //     this.consumeChildList = []
            // },
            // consumeMonthUpdate () {
            //     this.consumeMonth = true
            //     this.consumeMonthParams.channel_id = ''
            //     this.consumeMonthChildList = []
            // },
            consumeSubmit () {
                let list = []
                for (let item of this.consumeAllList) {
                    for (let items of item.children) {
                        if ((items.consume === 0 || items.consume > 0) && !items.disabled) {
                            list.push({
                                id: items.id ? items.id : 0,
                                date: this.$Date(this.consumeParams.date).format('YYYY-MM-DD'),
                                source_channel_id: items.source_channel_id,
                                consume: items.consume
                            })
                        }
                    }
                }
                // console.log(this.consumeAllList, list)
                this.disabled = true
                marketingconsumeupdateconsume({ list }).then(res => {
                    this.disabled = false
                    this.$Message.success('日消费录入成功');
                    // this.consumeChannel(this.consumeParams.channel_id)
                    this.askData()
                    this.consume = false
                    // 2022年1月11日周二14：56分，李晓峰在老万工位三要求此模态框提交关闭
                    // 2022年3月14日周二09：54分，张成成提需求弹框不关闭，点击渠道其他渠道不可选
                })
            },
            consumeCancel () {
                this.disabled = false
                this.consume = false
            },
            consumeMonthSubmit () {
                let list = []
                for (let item of this.consumeMonthAllList) {
                    for (let items of item.children) {
                        if ((items.consume === 0 || items.consume > 0) && !items.disabled) {
                            list.push({
                                id: items.id ? items.id : 0,
                                month: this.$Date(this.consumeMonthParams.date).format('YYYY-MM'),
                                source_channel_id: items.source_channel_id,
                                month_consume: items.consume
                            })
                        }
                    }
                }
                this.disabled = true
                marketingconsumeupdateconsumemonth({ list }).then(res => {
                    this.disabled = false
                    this.$Message.success('平均日消费录入成功');
                    this.askData()
                    this.consumeMonth = false
                    // 2022年1月11日周二14：56分，李晓峰在老万工位三要求此模态框提交关闭
                    // 2022年3月14日周二09：54分，张成成提需求弹框不关闭，点击渠道其他渠道不可选
                })
            },
            consumeMonthCancel () {
                this.disabled = false
                this.consumeMonth = false
            },
            unploadData(){
                this.modalStatus=true
            },
           
            handleUpload(){

            },
            handleFormatError(file) {
                this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。'
                })
            },
            handleSuccess(res, file) {
                // console.log(res,'res')
                // console.log(file,'file')
                if (res.code === 200) {
                this.$Message.success("浏览成功")
                this.imgSavePath=file.name
                this.file_type=res.data.file_type
                this.path=res.data.path
                } else {
                this.$Message.error(res.message)
                this.imgSavePath = ''
                this.file_type=''
                this.path=''
                this.$refs.upload.clearFiles()
                }
            },
            handleError(error, file) {
                this.$Message.error("数据导入失败！")
            },
            cancelModal(){
                this.imgSavePath = ''
                this.file_type=''
                this.path=''
                this.modalStatus=false
            },
            saveModal(){
                if (!this.imgSavePath) {
                    this.$Message.error("请选择文件")
                    return false
                }
                const params={
                    file_type:this.file_type,
                    path:this.path
                }
                saveConsume(params).then(res=>{
                    this.$Message.success('上传成功');
                    this.file_type=''
                    this.path=''
                    this.imgSavePath=''
                    this.modalStatus=false
                })
               
            },
            downMB() {
                window.open(this.url + '/excel/consume/consume.xlsx')
            },
        }
    };
</script>

<style lang="scss" scoped>

</style>
